﻿#include "dlgmain.h"
#include <QApplication>

QLibrary    *g_pLoadLogger = NULL;
QLibrary    *g_pLoadFrame = NULL;
ILogger     *g_pLogger = NULL;
IFramework  *g_pFramework = NULL;

bool Init();
bool Exit();

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    //
    if(!Init())
        return 0;
    qDebug() << "main thread id=" << QThread::currentThreadId();
    //
    DlgMain w;
    w.show();
    //
    int result = a.exec();
    //
    Exit();
    return result;
}

//load Logger.dll
bool Init()
{
    QDir dir;
    QString strPath = dir.currentPath();
    QString strLoggerpath = QString("%0/module/Logger.dll").arg(strPath);
    g_pLoadLogger = new QLibrary(strLoggerpath);
    if(g_pLoadLogger->load())
    {
        typedef ILogger* (*GetInstance)();
        GetInstance pGetInstance = (GetInstance)g_pLoadLogger->resolve("GetInstance");
        if(pGetInstance)
        {
            g_pLogger = pGetInstance();
            if(g_pLogger->Init())
            {
                strPath.append("/module/tFramework.dll");
                g_pLoadFrame = new QLibrary(strPath);
                if(g_pLoadFrame->load())
                {
                    typedef IFramework* (*GetInstance)();
                    GetInstance pGetInstance = (GetInstance)g_pLoadFrame->resolve("GetInstance");
                    if (pGetInstance)
                    {
                        g_pFramework = pGetInstance();
                        g_pLogger->SetFramework(g_pFramework);
                        g_pFramework->SetLogger(g_pLogger);
                        if(g_pFramework->Init())
                        {
                            return true;
                        }
                        else
                        {
                            g_pLogger->WriteLog(u8"Tm Load other dll fail!");
                        }
                    }
                }
            }
            else
                qDebug() << u8"Load Logger fail!";
        }
    }
    return false;
}

bool Exit()
{
    if(NULL != g_pFramework && NULL != g_pLoadFrame)
    {
        g_pFramework->UnInit();
        if(g_pLoadFrame->isLoaded())
        {
            g_pLoadFrame->unload();
            SAFE_DELETE(g_pLoadFrame);
            qDebug() << u8"unload tFramework";
        }
        g_pFramework = NULL;
    }
    if(NULL != g_pLogger && NULL != g_pLoadLogger)
    {
        g_pLogger->UnInit();
        if (g_pLoadLogger->isLoaded())
        {
            g_pLoadLogger->unload();
            SAFE_DELETE(g_pLoadLogger);
            qDebug() << u8"unload Logger";
        }
        g_pLogger = NULL;
    }
    return true;
}
